﻿using System;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;

namespace DMS.Base
{
    public class DbContext
    {
        private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

        private DbContext()
        {
           
        }
        
        [ThreadStatic]
        private static ConnectionWapper _connectionWapper;


        public static DbConnection CurrentConnection
        {
            get
            {
                if(_connectionWapper == null)
                {
                    _connectionWapper = new ConnectionWapper(ConnectionString);
                }
                else
                {
                    if(_connectionWapper.Connection.State == ConnectionState.Closed)
                    {
                        _connectionWapper.Connection.ConnectionString = ConnectionString;
                    }
                    
                }
                return _connectionWapper.Connection;
            }
        }

        public static TransactionScopeX NewTransactionScope()
        {
            // 事务问题还没有解决，暂时把事务去掉
            // var timeOut = new TimeSpan(0, 30, 0);
            // var ts = new TransactionScope(TransactionScopeOption.Required, timeOut);
            // return ts;
            return new TransactionScopeX();
        }
    }

    public class TransactionScopeX: IDisposable
    {
        public void Complete()
        {
            
        }

        public void Dispose()
        {
            
        }
    }

    /// <summary>
    /// 对象销毁时关闭数据库连接
    /// </summary>
    public class ConnectionWapper
    {
        public string ConnectionString { get; set; }

        public DbConnection Connection { get; set; }


        public ConnectionWapper(string connectionString)
        {
            this.ConnectionString = connectionString;
            this.Connection = new SqlConnection(this.ConnectionString);

        }

        ~ConnectionWapper()
        {
            try
            {
                if(this.Connection != null)
                {
                    this.Connection.Close();
                }
            }catch (Exception ex)
            {
                
            }
        }

    }
}
